package com.chensf.studydemo.common

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chensf.studydemo.R
import kotlinx.android.synthetic.main.fragment_pop_menu_demo.*
import kotlinx.android.synthetic.main.view_pop_demo_item.view.*

class PopMenuDemo : Fragment(){
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return layoutInflater.inflate(R.layout.fragment_pop_menu_demo,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        val adapter = PopAdapter()
        recyclerView.adapter = adapter
        adapter.listener = {
            PopMenuHelper.showMenu(requireContext(),it)
        }

    }

    private fun showMenu(anchor: View) {
        val layout = layoutInflater.inflate(R.layout.view_pop_window,view as ViewGroup,false)
        layout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        val popWindow = PopupWindow(layout,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)
        popWindow.height =layout.measuredHeight.coerceAtMost((anchor.rootView.height * 0.9).toInt())
        popWindow.run {
            setBackgroundDrawable(ColorDrawable())
            isFocusable = true
            isOutsideTouchable = true
            inputMethodMode = PopupWindow.INPUT_METHOD_NOT_NEEDED
            softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING
        }
        showAtLocation(popWindow, anchor)

//        PopupWindow().run {
//            width = ViewGroup.LayoutParams.MATCH_PARENT
//            contentView = onCreateView(author.context, this)
//                .apply {
//                    measure(makeDropDownMeasureSpec(width),
//                        View.MeasureSpec.UNSPECIFIED)
//                }
//            //窗口高度不能超过rootView高度的90%
//            setOnDismissListener {
//                height =
//                    contentView.measuredHeight.coerceAtMost((author.rootView.height * 0.9).toInt())
//                author.isSelected = false
//            }
//            setBackgroundDrawable(ColorDrawable())
//            isFocusable = true
//            isOutsideTouchable = true
//            inputMethodMode = PopupWindow.INPUT_METHOD_NOT_NEEDED
//            softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING
//            author.isSelected = true
//            showAtLocation(this, author)
//        }
    }

    private fun showAtLocation(window: PopupWindow, author: View) {
        val location = IntArray(2)
        val rootView = author.rootView
        author.getLocationInWindow(location)
        //Y坐标
        if (location[1] >= window.contentView.measuredHeight
            + SizeUtils.dp2px(requireContext(),80f)) {//menu显示在statusBar下
            //author的y大于窗口高度时,向上弹出,窗口起点等于y-height
            location[1] = location[1] - window.height
            (window.contentView as MenuBubbleLayout).setDirection(MenuBubbleLayout.BOTTOM)
        } else if (location[1] + window.height > rootView.height) {
            //author的y加上window的高度大于rootView的高度时,窗口要居中在整个屏幕,起点等于整个界面高度/2-窗口高度/2
            location[1] = rootView.height / 2 - window.height / 2
            (window.contentView as MenuBubbleLayout).setDirection(MenuBubbleLayout.BOTTOM)
        } else {
            location[1] += author.height
            (window.contentView as MenuBubbleLayout).setDirection(MenuBubbleLayout.TOP)
        }
        val x = location[0] + author.width / 2

        val halfWindowWidth = when (window.width) {
            ViewGroup.LayoutParams.MATCH_PARENT -> {
                rootView.width / 2
            }
            ViewGroup.LayoutParams.WRAP_CONTENT -> {
                window.contentView.measuredWidth / 2
            }
            else -> {
                window.width / 2
            }
        }
        //X坐标
        if (x + halfWindowWidth > rootView.width) {
            //author的X加上window的宽度大于rootView的宽度时,窗口要居中在整个屏幕,起点等于整个界面宽度/2-窗口宽度/2
            location[0] = rootView.width - halfWindowWidth * 2
        } else if (x >= halfWindowWidth) {
            //author的x大于窗口宽度时,向左弹出,窗口起点等于x-halfWindowWidth
            location[0] = x - halfWindowWidth
        } else {
            location[0] = 0
        }
        (window.contentView as MenuBubbleLayout).setTriangleOffset(x - (location[0] + halfWindowWidth))
        window.showAtLocation(author, Gravity.NO_GRAVITY, location[0], location[1])
    }

    private fun onCreateView(context: Context, popupWindow: PopupWindow): View {
        val container = MenuBubbleLayout(context).apply {
            setDirection(MenuBubbleLayout.LEFT)
            val padding = SizeUtils.dp2px(context, 16f)
            setPadding(padding, padding, padding, padding)
            setBackgroundColor(ContextCompat.getColor(context, R.color.M10))
            alpha = 0.9f
            setRadius(SizeUtils.dp2px(context, 4f))
        }
        val listView = RecyclerView(context).apply {
            overScrollMode = View.OVER_SCROLL_NEVER
            val padding = SizeUtils.dp2px(context, 5f)
            setPadding(padding, padding, padding, padding)
        }
        listView.layoutManager = GridLayoutManager(context, 5)
        listView.adapter = ListAdapter().apply {
            onItemClickListener = {position ->
                popupWindow.dismiss()
            }
        }
        container.addView(listView)
        return container
    }

    private fun makeDropDownMeasureSpec(measureSpec: Int): Int {
        val mode: Int = if (measureSpec == ViewGroup.LayoutParams.WRAP_CONTENT) {
            View.MeasureSpec.UNSPECIFIED
        } else {
            View.MeasureSpec.EXACTLY
        }
        return View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(measureSpec), mode)
    }


    private class ListAdapter() :
        RecyclerView.Adapter<OptionViewHolder>() {

        var onItemClickListener: ((position: Int) -> Unit)? = null

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OptionViewHolder {
            return OptionViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.mc_ui_recycler_item_menu_option, parent, false)
            )
        }

        override fun getItemCount(): Int {
            return 10
        }

        override fun onBindViewHolder(holder: OptionViewHolder, position: Int) {
            holder.itemView.setOnClickListener {
            }
        }

    }

    private class OptionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    class PopAdapter: RecyclerView.Adapter<PopHolder>(){
        var listener:((View)->Unit)?=null
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PopHolder {
            return PopHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_pop_demo_item,parent,false))
        }

        override fun onBindViewHolder(holder: PopHolder, position: Int) {
            if(position%2==0){
                holder.textView.text = "这是一条测试数据哈哈-$position"
            }else{
                holder.textView.text = "测试数据-$position"
            }

            holder.textView.setOnLongClickListener {
                listener?.invoke(holder.textView)
                true
            }
        }

        override fun getItemCount(): Int {
            return 50
        }

    }

    class PopHolder(itemView: View) :RecyclerView.ViewHolder(itemView){
        val textView:TextView = itemView.textView
    }
}